package com.zm.demo.ws.client;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.nio.file.Paths;
import java.util.List;

/**
 * @author dongxingli
 * Created on 2019/4/3 19:00
 */
public class JsonXmlUtils {

    private static final String ENCODING = "UTF-8";

    /**
     * JSON对象转的xml字符串-格式化 带空格 换行符 输出到文件可读性好
     *
     * @param json JSON对象
     * @return 漂亮的xml字符串
     */
    public static String jsonToFormatXml(JSONObject json) {
        StringWriter formatXml = new StringWriter();
        try {
            Document document = jsonToDocument(json);
            /* 格式化xml */
            OutputFormat format = OutputFormat.createPrettyPrint();
            // 设置缩进为4个空格
            format.setIndent(" ");
            format.setIndentSize(4);
            XMLWriter writer = new XMLWriter(formatXml, format);
            writer.write(document);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return formatXml.toString();
    }

    /**
     * JSON对象转xml字符串-不带空格换行符
     *
     * @param json JSON对象
     * @return xml字符串
     * @throws SAXException
     */
    public static String JsonToXml(JSONObject json) {
        return jsonToDocument(json).asXML();
    }

    /**
     * JSON对象转Document对象
     *
     * @param json JSON对象
     * @return Document对象
     */
    public static Document jsonToDocument(JSONObject json) {
        Document document = DocumentHelper.createDocument();
        document.setXMLEncoding(ENCODING);
        for (String rootKey : json.keySet()) {
            Element root = DocumentHelper.createElement(rootKey);
            addJsonObjectElement(json.getJSONObject(rootKey), root);
            document.add(root);
            // root对象只能有一个，多个时只读一个
            break;
        }
        return document;
    }

    /**
     * 添加JSONArray Element
     *
     * @param jsonArray 传入的json数组
     * @param nodeName  节点名称
     * @param arrRoot   上层节点
     */
    private static void addJsonArrayElement(JSONArray jsonArray, String nodeName, Element arrRoot) {

        for (Object aJsonArray : jsonArray) {
            JSONObject jsonObject = (JSONObject) aJsonArray;
            Element node = DocumentHelper.createElement(nodeName);
            // 继续遍历
            for (String key : jsonObject.keySet()) {
                Element element = DocumentHelper.createElement(key);
                Object child = JSON.toJSON(jsonObject.get(key));
                if (child instanceof JSONArray) {
                    // 递归
                    addJsonArrayElement(jsonObject.getJSONArray(key), key, node);
                } else if (child instanceof JSONObject) {
                    addJsonObjectElement(jsonObject.getJSONObject(key), element);
                    node.add(element);
                } else {
                    element.setText(jsonObject.getString(key));
                    node.add(element);
                }
            }
            arrRoot.add(node);
        }

    }


    /**
     * 添加JSONObject Element
     *
     * @param json JSON对象
     * @param root 上层节点
     * @return Element对象
     */
    private static void addJsonObjectElement(JSONObject json, Element root) {

        for (String key : json.keySet()) {
            Element node = DocumentHelper.createElement(key);
            Object child = json.get(key);
            if (child instanceof JSONObject) {
                addJsonObjectElement(json.getJSONObject(key), node);
                root.add(node);
            } else if (child instanceof List) {
                addJsonArrayElement(json.getJSONArray(key), key, root);
            } else {
                node.setText(json.getString(key));
                root.add(node);
            }
        }

    }

    /**
     * XML字符串转JSON对象
     *
     * @param xml xml字符串
     * @return JSON对象
     * @throws DocumentException
     */
    public static JSONObject xmlToJson(String xml) throws DocumentException {
        JSONObject json = new JSONObject();
        SAXReader reader = new SAXReader();
        Document document = reader.read(new StringReader(xml));
        Element root = document.getRootElement();
        json.put(root.getName(), elementToJson(root));

        return json;
    }

    /**
     * Element对象转JSON对象
     *
     * @param element Element对象
     * @return JSON对象
     */
    public static JSONObject elementToJson(Element element) {
        JSONObject json = new JSONObject();
        for (Object child : element.elements()) {
            Element e = (Element) child;
            if (e.elements().isEmpty()) {
                json.put(e.getName(), e.getText());
            } else {
                json.put(e.getName(), elementToJson(e));
            }
        }

        return json;
    }
}